package softtech.apps.autoanswerphonecall;

import java.io.File;
import softtech.apps.model.DatabaseHandler;
import softtech.apps.model.Message;
import softtech.apps.model.RowRecord;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

public class DialogAddSms extends Activity {

	private EditText edtMsgTitle, edtMsgContent;

	private TextView tvFunction;

	private CheckBox checkBoxSetDefaultMsg;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Remove title bar
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		// set view
		setContentView(R.layout.activity_dialog_add_sms);

		// find view id
		Button btCancel = (Button) findViewById(R.id.bt_cancel);
		Button btSave = (Button) findViewById(R.id.bt_save);

		edtMsgTitle = (EditText) findViewById(R.id.edt_sms_title);

		edtMsgTitle.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					getWindow()
							.setSoftInputMode(
									WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
				}
			}
		});

		edtMsgContent = (EditText) findViewById(R.id.edt_sms_content);

		checkBoxSetDefaultMsg = (CheckBox) findViewById(R.id.checkBoxSetDefault);

		tvFunction = (TextView) findViewById(R.id.tv_function);

		// get type request
		final Intent intent = getIntent();
		final int requestCode = intent.getIntExtra("requestCode",
				MainActivity.REQUEST_CODE_DIALOG_ADD_SMS);

		btCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				setResult(RESULT_CANCELED);
				finish();
			}
		});

		if (requestCode == MainActivity.REQUEST_CODE_DIALOG_EDIT_SMS
				|| requestCode == MainActivity.REQUEST_CODE_DIALOG_ADD_SMS) {

			tvFunction.setText("Edit message");

			String titleMsg = intent
					.getStringExtra(DatabaseHandler.MSG_KEY_TITLE);
			if (requestCode == MainActivity.REQUEST_CODE_DIALOG_EDIT_SMS
					&& titleMsg.compareTo("Sms Default") == 0) {
				edtMsgTitle.setEnabled(false);
			}

			// title msg
			edtMsgTitle.setText(titleMsg);

			// content msg
			edtMsgContent.setText(intent
					.getStringExtra(DatabaseHandler.MSG_KEY_CONTENT));

			if (requestCode == MainActivity.REQUEST_CODE_DIALOG_EDIT_SMS) {
				checkBoxSetDefaultMsg.setVisibility(View.GONE);
			}

			if (intent.getIntExtra(DatabaseHandler.MSG_KEY_DEFAULT, 0) == 1) {
				checkBoxSetDefaultMsg.setChecked(true);
			} else {
				checkBoxSetDefaultMsg.setChecked(false);
			}

			btSave.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// return data, put it to intent
					// save msg to database

					DatabaseHandler dbHandler = new DatabaseHandler(
							getApplicationContext());
					Message msg = new Message();

					msg.set_title(edtMsgTitle.getText().toString());

					if (msg.get_title().isEmpty()) {
						msg.set_title(dbHandler.VALUE_TITLE_SMS_DEFAULT);
					}

					msg.set_content(edtMsgContent.getText().toString());

					if (msg.get_content().isEmpty()) {
						msg.set_content(dbHandler.VALUE_CONTENT_SMS_DEFAULT);
					}
					int isDefault = checkBoxSetDefaultMsg.isChecked() == true ? 1
							: 0;

					msg.set_isDefault(isDefault);

					Message msgDefault = dbHandler.getMessageDefault();

					if (isDefault == 1) {

						if (msgDefault != null) {

							msgDefault
									.set_isDefault(dbHandler.VALUE_NON_DEFAULT);

							dbHandler.updateMessage(msgDefault);
						} else {

							msg.set_isDefault(dbHandler.VALUE_IS_DEFAULT);
						}
					}

					if (edtMsgTitle.getText().toString().trim()
							.compareTo("Sms Default") == 0) {
						AlertDialog.Builder builder = new AlertDialog.Builder(
								DialogAddSms.this);
						builder.setTitle("Duplication!");
						builder.setMessage(
								"Title not coincide with the default messaging system !")
								.setCancelable(false)
								.setPositiveButton("Ok",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
											}
										});
						Dialog aDialog = builder.create();
						aDialog.show();
						return;
					}

					if (requestCode == MainActivity.REQUEST_CODE_DIALOG_ADD_SMS) {

						msg.set_id(-1);

						dbHandler.insertMessage(msg);
					} else if (requestCode == MainActivity.REQUEST_CODE_DIALOG_EDIT_SMS) {

						msg.set_id(intent.getIntExtra(
								DatabaseHandler.MSG_KEY_ID, 1));

						dbHandler.updateMessage(msg);
					}

					setResult(RESULT_OK);
					finish();
				}
			});
		} else if (requestCode == MainActivity.REQUEST_CODE_DIALOG_ADD_RECORD
				|| requestCode == MainActivity.REQUEST_CODE_DIALOG_EDIT_RECORD) {

			tvFunction.setText("Record");

			TextView textViewContent = (TextView) findViewById(R.id.textViewContent);
			textViewContent.setVisibility(View.GONE);
			edtMsgContent.setVisibility(View.GONE);

			final String path_record = intent.getStringExtra("pathRecord");

			int ix = path_record.lastIndexOf("/");

			final String nameRecord = path_record.substring(ix + 1,
					path_record.length());
			
			if (requestCode == MainActivity.REQUEST_CODE_DIALOG_EDIT_RECORD) {
				checkBoxSetDefaultMsg.setVisibility(View.GONE);
			}

			final String name[] = nameRecord.split("-");

			edtMsgTitle.setText(name[0]);
			edtMsgTitle.setMinLines(1);
			edtMsgTitle.setMaxLines(5);

			btSave.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					String path_end = path_record;

					if (edtMsgTitle.getText().toString().trim().length() > 0) {
						path_end = path_end.replace(name[0], edtMsgTitle
								.getText().toString().trim());
					}

					int index = path_end.lastIndexOf("/");
					
					String name = path_end.substring(index + 1, path_end.indexOf(".") - 1);
					
					if(moveFile(path_record, path_end) && !name.split("-")[0].contains("-")){
						

						if (requestCode == MainActivity.REQUEST_CODE_DIALOG_ADD_RECORD
								&& checkBoxSetDefaultMsg.isChecked()) {
							DatabaseHandler dbHandler = new DatabaseHandler(
									getApplicationContext());
							dbHandler.updateNameRecordDefault(name, path_end);

						} else if (requestCode == MainActivity.REQUEST_CODE_DIALOG_EDIT_RECORD) {

							DatabaseHandler dbHandler = new DatabaseHandler(
									getApplicationContext());

							RowRecord rr = dbHandler.getNameRecordDefault();
							String nameDefault = rr.getmFileName() + "-.mp3";

							if (nameRecord.compareTo(nameDefault) == 0) {

								dbHandler.updateNameRecordDefault(name, path_end);
							}

						}
						setResult(RESULT_OK);
						finish();
					}else{
						AlertDialog.Builder builder = new AlertDialog.Builder(
								DialogAddSms.this);
						builder.setTitle("ERROR !");
						builder.setMessage(
								"Name contains characters invalid!")
								.setCancelable(false)
								.setPositiveButton("Ok",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
											}
										});
						Dialog aDialog = builder.create();
						aDialog.show();
						return;
					}

					
				}

			});

		}

	}
	
	
	public boolean moveFile(String oldfilename, String newFolderPath) {
		File file = new File(oldfilename);
		File file2 = new File(newFolderPath);
		
		boolean success = false;
		if (!file2.exists()) {
			
			success = file.renameTo(file2);
			
			if(success){

				file.delete();
			}
		}else{
			success = true;
		}
		
		return success;
	}
}
